import {AsyncStorage} from 'react-native'
import {AuthModel} from "./model";
import {kAuthorization} from "../constant";
import Request from "../utils/Request";

const STORAGE_KEY = "STORAGE_KEY_group";
export default {
    namespace: 'group',
    state: {
        loading: false,
        postList: [],
        comments: [],
        praise: []
    },
    reducers: {
        save(state, {payload}) {
            return {...state, ...payload}
        }
    },
    effects: {


        // 保存到本地
        * saveToStorage({payload}, {call}) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload))
        },

        // 本地恢复
        * restoreFromStorage({payload}, {call, put, select}) {
            const data = yield call(AsyncStorage.getItem, STORAGE_KEY);
            yield put({
                type: 'save',
                payload: {...JSON.parse(data)}
            });
        },
        //清除数据
        * clear({payload}, {put}) {
        },

        //获取群组动态列表
        * fetchGroupPosts({payload}, {call, put, select}) {
            const auth: AuthModel = yield select(state => state.auth);
            let groupId = payload.groupId;
            delete  payload.groupId;
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            const res: postItem [] = yield call(Request.get, Request.getApi().groupPosts + `/${groupId}`, payload);
            if (res) {
                const postList = res;
                yield put({
                    type: 'save',
                    payload: {
                        postList
                    }
                })

            }
        }
    },
    subscriptions: {
        setup({dispatch}) {

        }
    },
};
